local WebSockets = require(SCRIPTS_DIR .. ".network.WebSockets");
local WebNet = class("WebNet")
function WebNet:ctor()
    -- body
    self.messageType = WebSockets.BINARY_MESSAGE;
    self.websocket = nil;
    self.socketIsOk = false;
end

function WebNet:connectSocket(host,protocol)
    -- body
    if self.websocket then return end
    self.websocket = WebSockets.new(host,protocol);
    self.websocket:addEventListener(WebSockets.OPEN_EVENT, handler(self, self.onOpen));
    self.websocket:addEventListener(WebSockets.MESSAGE_EVENT, handler(self, self.onMessage));
    self.websocket:addEventListener(WebSockets.CLOSE_EVENT, handler(self, self.onClose));
    self.websocket:addEventListener(WebSockets.ERROR_EVENT, handler(self, self.onError));
end

function WebNet:onOpen(event)
    -- body
    mgrs.log:printNotice("WebSocketMgr:onOpen")
    self.socketIsOk = true;
    mgrs.proto:socketSucess(self);
    --mgrs.event:dispatchEvent({name = enums.Event.WebSocketOpen});
end

function WebNet:onMessage(event)
    -- body
    if WebSockets.BINARY_MESSAGE == event.messageType then
        local message = event.message
        mgrs.proto:parseMessage(message)
    else
        mgrs.log:printNotice("收到数据:%s",event.message)
        local message = json.decode(event.message);
        mgrs.proto:receive(message.msgid,message);
    end
end

function WebNet:onClose(event)
    -- body
    mgrs.log:printNotice("WebSocketMgr:onClose");
    self.websocket = nil
    self.socketIsOk = false;
    mgrs.proto:socketClosed(self);
end

function WebNet:onError(event)
    -- body
     mgrs.log:printWarn("WebSocket onError %s", event.error)
    self.websocket = nil
    self.socketIsOk = false;
    mgrs.proto:socketError(self);
end


function WebNet:closeSocket()
    -- body
    if self.websocket then
        self.websocket:close();
    end
end

function WebNet:sendData(data)
    -- body
    if self.websocket and self.socketIsOk then
        if self.messageType == WebSockets.TEXT_MESSAGE then
            if type(data) == "table" then
                data = json.encode(data);
            elseif type(data) == "number" then
                data = json.encode({msgid = data});
            end
        end
        mgrs.log:printNotice("发送数据:%s",data);
        self.websocket:send(data,self.messageType);
    end
end

return WebNet;